package com.yxjme.redrainlibrary.v;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.widget.RelativeLayout;

import com.yxjme.redrainlibrary.R;
import com.yxjme.redrainlibrary.m.RedPacket;

import java.util.List;
import java.util.Random;

public class LaunchRedPacketView extends RelativeLayout {

    /*红包*/
    private Drawable drawable ;
    /*红包图片宽高*/
    private int dWidth;
    private int dHeight;
    /*当前view的宽高*/
    private int mViewWidth;
    private int mViewHeight;
    /*增强点击范围*/
    private int addTouch = 30 ;
    /*下落时间*/
    private int during = 4000 ;
    /*设置下落的时候有快有慢*/
    private int speedDuring = 1000 ;
    /*点击的时候在屏幕中的位置*/
    private float dx , dy ;

    private int[] drawables={
            R.mipmap.icon_jinbi,
            R.mipmap.icon_jinbi1
    };


    /**
     * 活动金币雨样色
     * @param drawables
     */
    public void setDrawables(int[] drawables) {
        this.drawables = drawables;
    }

    public void setAddTouch(int addTouch) {
        this.addTouch = addTouch;
    }

    public void setSpeedDuring(int speedDuring) {
        this.speedDuring = speedDuring;
    }

    public void setDuration(int during) {
        this.during = during;
    }

    public LaunchRedPacketView(Context context) {
        this(context,null);
    }

    public LaunchRedPacketView(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public LaunchRedPacketView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        drawable = context.getResources().getDrawable(drawables[new Random().nextInt(drawables.length)]);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        mViewWidth = getMeasuredWidth();
        mViewHeight = getMeasuredHeight() ;
        super.onLayout(changed, l, t, r, b);
    }


    /**
     * @param list
     * @param <T>
     */
    public <T> void lunchCount(List<T> list){
        if (list!=null&&list.size()>0){
            for (T t:list){
                lunch(t);
            }
        }
    }



    /**
     * 测试
     *
     * @param <T>
     */
    public <T> void lunchCount(final int num){
        for (int i = 0 ; i < num ;i++){
            lunch(i);
        }
    }


    /**
     * 插值器
     */
    private Interpolator[] interpolator={
            new LinearInterpolator(),
            new AccelerateInterpolator(),
            new DecelerateInterpolator(),
            new AccelerateDecelerateInterpolator()
    };



    public Interpolator getInterpolator(){
        return interpolator[new Random().nextInt(4)];
    }


    /**
     * 设置金币图
     */
    public void setDrawable() {
        this.drawable = getResources().getDrawable(drawables[new Random().nextInt(drawables.length)]);
        /*获取图片宽高*/
        if (drawable!=null){
            dWidth = drawable.getIntrinsicWidth() ;
            dHeight = drawable.getIntrinsicHeight();
        }
    }


    /**
     * 设置金币大小倍率
     * 0.1 - 1
     * @param radio
     */
    float radio = 0.8f;
    public LaunchRedPacketView setRedPacketSize(float radio){
        this.radio=radio;
        return this;
    }



    /**
     * 发射红包
     *
     * 每次发射时单个
     */
    private  <T> void lunch(T t){

        setDrawable();

        final RedPacket<T> redPacket = new RedPacket(getContext());
        redPacket.redInfo = t ;
        redPacket.setPadding(addTouch,addTouch,addTouch,0);
        redPacket.setImageDrawable(drawable);
        LayoutParams layoutParams = new LayoutParams((int)((dWidth+addTouch)*radio),(int)((dHeight+addTouch)*radio));
        //设置位置
        layoutParams.addRule(ALIGN_PARENT_TOP, TRUE);
        redPacket.setLayoutParams(layoutParams);
        addView(redPacket);


        /*随机显示位置*/
        MarginLayoutParams marginLayoutParams = (MarginLayoutParams) redPacket.getLayoutParams();
        int left = mViewWidth - dWidth/2;
        marginLayoutParams.leftMargin = (left <= 0 ? 0 : new Random().nextInt(left));
        marginLayoutParams.topMargin = -dHeight;


        /*添加动画*/
        final Animator set = addAnimator(redPacket);
        set.start();

        /*结束之后销毁*/
        set.addListener(new AnimatorListenerAdapter(){
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                removeView(redPacket);
            }
        });

        redPacket.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                dx = event.getRawX();
                dy = event.getRawY();
                if (onAddClickListener!=null){
                    onAddClickListener.onClick(redPacket);
                    onAddClickListener.onPointXY(dx,dy);
                    redPacket.setVisibility(INVISIBLE);
                    redPacket.setEnabled(false);
                }
                return true;
            }
        });
    }




    /**
     * 设置动画
     *
     * @param target
     */
    private Animator addAnimator(View target)  {
        AnimatorSet set = new AnimatorSet();
//        AnimatorSet enterSet = getEnterSet(target);
        ValueAnimator bezierValueAnimator = getValueAnimator(target);
        set.playSequentially(bezierValueAnimator);
        set.setInterpolator(getInterpolator());
        set.setTarget(target);
        return set;
    }




    /**
     * 设置贝赛尔曲线动画
     *
     * @param target
     * @return
     */
    private ValueAnimator getValueAnimator(final View target) {
        //贝赛尔估值器
        ValueAnimator animator = ValueAnimator.ofFloat(-(dHeight+addTouch),mViewHeight+dHeight);

        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float v= (float) animation.getAnimatedValue();
                target.setTranslationY(v);
            }
        });
        animator.setTarget(target);
        animator.setDuration(during+new Random().nextInt(speedDuring));
        return animator;
    }



    /**
     * 入场动画
     *
     * @param target
     * @return
     */
    private AnimatorSet getEnterSet(View target) {
        try {
            AnimatorSet enterSet = new AnimatorSet();
            enterSet.playTogether(
                    ObjectAnimator.ofFloat(target, View.ALPHA, 0, 1f),
                    ObjectAnimator.ofFloat(target, View.SCALE_X, 0.1f, 0.8f),
                    ObjectAnimator.ofFloat(target, View.SCALE_Y, 0.1f, 0.8f)
            );
            enterSet.setDuration(500);
            enterSet.setInterpolator(new LinearInterpolator());
            enterSet.setTarget(target);
            return enterSet;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



    public interface OnAddClickListener{
        void onClick(RedPacket redPacket);
        void onPointXY(float x , float y);
    }

    private OnAddClickListener onAddClickListener;

    public void setOnAddClickListener(OnAddClickListener onAddClickListener) {
        this.onAddClickListener = onAddClickListener;
    }
}
